<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader v-on:addTodo="getAddedTodo" />
        <MyList :todos="todos" />
        <MyFooter :todos="todos" ref="footerSelect" />
      </div>
    </div>
  </div>
</template>

<script>
import MyHeader from "./components/MyHeader";
import MyList from "./components/MyList.vue";
import MyFooter from "./components/MyFooter.vue";
export default {
  name: "App",
  data() {
    return {
      todos: JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  components: {
    MyHeader,
    MyList,
    MyFooter,
  },
  watch: {
    todos: {
      deep: true, //开启深度监听
      handler(newVal) {
        localStorage.setItem("todos", JSON.stringify(newVal));
      },
    },
  },
  methods: {
    // 通过MyHeader组件添加todos
    getAddedTodo(todo) {
      this.todos.unshift(todo);
    },
    // 通过MyFooter组件确定是否全选
    getselectAll(isAll) {
      for (let todo of this.todos) {
        todo.done = isAll;
      }
    },

    // 通过MyFooter组件确定是否清除已完成事项
    clearDone() {
      this.todos = this.todos.filter((todo) => !todo.done);
    },

    // 通过全局事件总线删除MyItem组件传入的id
    deleteTodo(id) {
      this.todos = this.todos.filter((todo) => todo.id !== id);
    },

    // 通过全局事件总线修改新编辑的name;
    editTodo(id, name) {
      for (let todo of this.todos) {
        if (todo.id == id) todo.name = name;
      }
    },
  },

  mounted() {
    // 通过MyFooter组件确定是否全选
    this.$refs.footerSelect.$on("selectAll", this.getselectAll);
    // 通过MyFooter组件确定是否清除已完成事项
    this.$refs.footerSelect.$on("clearDone", this.clearDone);

    // 全局事件总线和MyItem通信 VueComponent.prototype.__proto__ = Vue.prototype
    this.$bus.$on("deleteTodo", this.deleteTodo);
    // 通过全局事件总线修改新编辑的name;
    this.$bus.$on("editTodo", this.editTodo);
  },

  beforeDestroy() {
    this.$refs.footerSelect.$off(["selectAll", "clearDone"]);
    this.$bus.$off(["deleteTodo", "editTodo"]);
  },
};
</script>

<style lang="css">
.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-edit {
  color: #fff;
  background-color: skyblue;
  border: 1px solid skyblue;
  margin-right: 2px;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
